﻿namespace GoogleOAuth.Models
{
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;

    using Newtonsoft.Json;

    public static class HttpExtensions
    {
        public static async Task<T> GetValueFromRequest<T>(this HttpWebRequest request, string postData = null)
        {
            T returnValue = default(T);

            if (!string.IsNullOrEmpty(postData))
            {
                byte[] requestBytes = Encoding.UTF8.GetBytes(postData);

                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = requestBytes.Length;

                using (Stream postStream = await request.GetRequestStreamAsync())
                {
                    await postStream.WriteAsync(requestBytes, 0, requestBytes.Length);
                }
            }
            else
            {
                request.Method = "GET";
            }

            var response = await request.GetResponseAsync();

            if (response != null)
            {
                using (Stream receiveStream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(receiveStream))
                    {
                        string json = await reader.ReadToEndAsync();

                        return JsonConvert.DeserializeObject<T>(json);
                    }
                }
            }

            return returnValue;
        }
    }
}
